﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GordonKristan.codeclean
{
	class AlphabetizingModule
	{
		private String document;

		/// <summary>
		/// Constructor that takes an array of strings.
		/// Performs the sort operation as well.
		/// </summary>
		/// <param name="aDoc">Document with lines</param>
		/// <param name="startline">Start of sorted lines</param>
		/// <param name="endline">End of sorted lines</param>
		public AlphabetizingModule(String aDoc, int startline, int endline)
		{
			document = aDoc;
			performSort(startline, endline);
		}

		/// <summary>
		/// Sorts the lines in alphabetical order.
		/// </summary>
		private void performSort(int startline, int endline)
		{
			//The selection could be 'reversed'
			if (startline > endline)
			{
				int temp = endline;
				endline = startline;
				startline = temp;
			}
			//Get the start of the first line
			int newlines = 0;
			int start = 0;
			while (newlines < startline)
			{
				start = document.IndexOf("\r\n", start) + 2;
				newlines++;
			}
			//Get the end of the last line
			newlines = 0;
			int end = 0;
			while (newlines <= endline)
			{
				end = document.IndexOf("\r\n", end) + 2;
				newlines++;
			}
			//Get only the lines to sort
			String chunk = document.Substring(start, end - start);
			//Split them into an array
			String[] lines = chunk.Split('\n');
			//That stripped the newline. Add it back.
			for (int i = 0; i < lines.Length - 1; ++i)
			{
				lines[i] += "\n";
			}
			//Sort them
			Array.Sort(lines);
			String done = "";
			//Concatenate all of the lines
			foreach (String s in lines)
			{
				done += s;
			}
			//Replace the old ones with the new ones
			document = replaceSubstring(document, start, end - start, done);
		}

		/// <summary>
		/// Returns the sorted lines.
		/// </summary>
		/// <returns>Document with specified lines sorted</returns>
		public String getText()
		{
			return document;
		}

		/// <summary>
		/// Replaces a portion of string with a new string.
		/// Use -1 as length to replace rest of string from start onwards.
		/// </summary>
		/// <param name="aDoc">String to perform replacement on</param>
		/// <param name="start">Start of substring to replace</param>
		/// <param name="length">Length of substring to replace</param>
		/// <param name="replace">String to replace with</param>
		private String replaceSubstring(String aDoc, int start, int length, String replace)
		{
			if (length == 0)
			{
				return aDoc;
			}
			String begin, end;
			if (start == 0)
			{
				begin = "";
			}
			else
			{
				begin = aDoc.Substring(0, start);
			}
			if (length == -1)
			{
				end = "";
			}
			else
			{
				end = aDoc.Substring(start + length);
			}
			return begin + replace + end;
		}
	}
}
